package com.bdsoft.auth.controller;

import cn.hutool.jwt.JWTUtil;

import com.bdsoft.auth.Service.LoginService;
import com.bdsoft.auth.entity.User;
import com.bdsoft.auth.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/auth")
@Tag(name = "登陆相关接口")
public class LoginController {
    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Operation(summary = "用户登陆")
    @PostMapping("/login")
    public Map<String, Object> login(@Parameter(name = "userName", description = "用户名") @RequestParam String userName, @Parameter(name = "userPassword", description = "密码") @RequestParam String userPassword
    ) {

        User user = loginService.findByUsername(userName);
        Map<String, Object> result = new HashMap<>();
        if (user == null || !user.getPassword().equals(userPassword)) {
            result.put("success", false);
            result.put("msg", "用户名或密码错误");

            return result;
        }

        String token = JwtUtil.generateToken(user.getUsername(),user.getId());

        result.put("success", true);
        result.put("token", token);
        result.put("userId", user.getUsername());

        // 获取角色（添加空检查）
        List<Map<String, Object>> roles = loginService.findUserRole(user.getId());
        if (!roles.isEmpty()) {
            result.put("role", roles.get(0).get("role_code"));
        }

        return result;
    }

    @Operation(summary = "用户登出")
    @PostMapping("/logout")
    public Map<String, Object> logout(@RequestHeader("Authorization") String token) {
        Map<String, Object> result = new HashMap<>();
        try {
            String realToken = token.replace("Bearer ", "");
            // 解析token过期时间（假设JwtUtil有解析过期时间的方法）
            long expire = JwtUtil.getExpire(realToken); // 单位：秒
            long now = System.currentTimeMillis() / 1000;
            long ttl = expire - now;
            if (ttl > 0) {

                redisTemplate.opsForValue().set(
                        "blacklist:" + realToken,
                        realToken,
                        ttl,
                        TimeUnit.SECONDS
                );
            }
            result.put("code", 200);
            result.put("msg", "登出成功");
        } catch (Exception e) {
            System.out.println(e);
            result.put("code", 500);
            result.put("msg", "登出失败");
        }
        return result;
    }
} 